
package w83b.w83bManager;

import java.io.BufferedWriter;
//import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import w83b.w83bUtilidadesComunes.W83bDateUtils;
import w83b.w83bUtilidadesComunes.W83bProperties;
import w83b.w83bUtilidadesComunes.W83bStringUtil;
import w83b.w83bUtilidadesComunes.W83bWebServiceCall;
import w83b.w83bUtilidadesComunes.W83bClsConstantes;
import w83b.w83bUtilidadesComunes.W83bClsTrazas;
import w83b.w83bUtilidadesComunes.W83bException;

import java.util.logging.Level;
import java.util.logging.Logger;



public class W83bEjGvDocumento implements Serializable{//NOPMD

	private static final long serialVersionUID = 1L;	
	
	public static String obtenerFirmasimple(String sessionToken, String certificateID,String txt) {
		String result = "";
		try {
		
			if(W83bProperties.getProperty("w83b","dokusi.firma.servidor.ACTIVE").equals("true")){
				String jpdMethod = "createSimplSignByteArray";

				BufferedWriter out = new BufferedWriter(new FileWriter(W83bProperties.getProperty("w83b", "file.out")+"obtenerFirma.txt",true));
				out.write("\r\n\r\n"+"textopreparado=>"+txt+"$$$");
				
				
				
				MessageFactory mfactory = MessageFactory.newInstance();

				SOAPMessage message = mfactory.createMessage();

				SOAPPart soapPart = message.getSOAPPart();

				SOAPEnvelope envelope = soapPart.getEnvelope();
				
				SOAPBody body = envelope.getBody();
				
				Name name = envelope.createName(jpdMethod, "",
						"http://www.openuri.org/");
				
				SOAPBodyElement element = body.addBodyElement(name);
				;
				SOAPElement symbol = element.addChildElement(envelope
						.createName("sessionToken"));
				
				symbol.addTextNode(sessionToken);
				
				symbol = element.addChildElement(envelope.createName("certificateID"));
				
				symbol.addTextNode(certificateID);
				
				symbol = element.addChildElement(envelope.createName("simplDocums"));
				
				symbol.addTextNode(txt);
				
	
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				
				SOAPConnection con = factory.createConnection();
				
				
				String url = W83bProperties.getProperty("w83b","url.ws.Q99vDigitalSignatureJWS");
				
				if (log.isLoggable(Level.INFO)){
					log.info("sessionToken="+sessionToken);
					log.info("certificateID="+certificateID);
					log.info("txt codigicado base64 para la firma"+txt);
				}
				//W83bClsTrazas.trazaError(null, " **** 21  " );
	
				SOAPMessage responseWebServ = con.call(message, url);
				
				result = W83bWebServiceCall.getResultado(responseWebServ);

				if (result.startsWith("Fallo:")){
					result="";
				}

				
				out.write("RESULTADO:" + result);
				
				 out.close();
			}else{
				result = "Hola Mundo";
			}

			if (log.isLoggable(Level.INFO)){
				log.info("Result obtener firma simple servidor-->" + result);
			}

			
				
			
			
			return result;
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	
	
	public static String obtenerJustificante(String numRegES) {
		String result = "";
		try {
			
			
				String jpdMethod = "getRegistryReceipt";
				
				
				MessageFactory mfactory = MessageFactory.newInstance();
				
				SOAPMessage message = mfactory.createMessage();
				
				SOAPPart soapPart = message.getSOAPPart();
				
				SOAPEnvelope envelope = soapPart.getEnvelope();
				
				SOAPBody body = envelope.getBody();
				
				Name name = envelope.createName(jpdMethod, "",
				"http://www.openuri.org/");
				
				SOAPBodyElement element = body.addBodyElement(name);
				
				SOAPElement symbol = element.addChildElement(envelope
						.createName("sRegistryNumber"));
				
				symbol.addTextNode(numRegES);
				
				
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				
				SOAPConnection con = factory.createConnection();
			
				String url = W83bProperties.getProperty("w83b","url.ws.justificante");
				
				if (log.isLoggable(Level.INFO)){
					log.info("numRegES="+numRegES);
				
				}
				
				
				SOAPMessage responseWebServ = con.call(message, url);
				
				result = W83bWebServiceCall.getResultado(responseWebServ);
				if (log.isLoggable(Level.INFO)){
					log.info("Result -->" + result);
				}
				
				String firma=W83bStringUtil.obtenerPatronInicioFin(result, W83bClsConstantes.ETIQUETAFIRMAINICIO,W83bClsConstantes.ETIQUETAFIRMAFIN);
			
			if (log.isLoggable(Level.INFO)){
				log.info("Result obtener justificante-->" + firma);
			}
		
			
			
			return firma;
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	

	
	public static String generarNotificacion(String sessionToken, String tareaNotificar) throws W83bException{
		String result = "";
		
		
		
		try {
			W83bClsTrazas.trazaError(null, " @@@@@@  1 generarNotificacion",null  );
			  // A partir del objeto File creamos el fichero físicamente
            Date fecha=new Date();
            String sfecha=W83bDateUtils.dateTimeToString(fecha);
          
    		BufferedWriter out = new BufferedWriter(new FileWriter(W83bProperties.getProperty("w83b", "file.out")+"generarNotificacion.txt",true));
    		 out.write(sfecha+"\r\n\r\n"+"sessionToken=>"+sessionToken+"\r\n\r\n"+"tareaNotificar=>"+tareaNotificar+"\r\n\r\n");
           out.close();
						
			if(W83bProperties.getProperty("w83b","notificar.crear.ACTIVE").equals("true")){
				W83bClsTrazas.trazaError(null, " @@@@@@  2 generarNotificacion",null  );
				String jpdMethod = W83bProperties.getProperty("w83b","notificacion.procedure.crear");
				W83bClsTrazas.trazaError(null, " @@@@@@  3 generarNotificacion",null  );
				MessageFactory mfactory = MessageFactory.newInstance();
				SOAPMessage message = mfactory.createMessage();
				SOAPPart soapPart = message.getSOAPPart();
				SOAPEnvelope envelope = soapPart.getEnvelope();
				SOAPBody body = envelope.getBody();
				Name name = envelope.createName(jpdMethod, "",
						"http://www.openuri.org/");
				
				SOAPBodyElement element = body.addBodyElement(name);
				
				SOAPElement symbol = element.addChildElement(envelope.createName("sessionToken"));
				
				symbol.addTextNode(sessionToken);
				
				symbol = element.addChildElement(envelope.createName("tareaNotificar"));
				
				symbol.addTextNode(tareaNotificar);
				
				W83bClsTrazas.trazaError(null, " @@@@@@  4 generarNotificacion",null  );
								
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				
				SOAPConnection con = factory.createConnection();
				
				String url = W83bProperties.getProperty("w83b",
						"url.ws.crearNotificacion");
				W83bClsTrazas.trazaError(null, " @@@@@@  5 generarNotificacion",null  );
				
				if (log.isLoggable(Level.INFO)){
					log.info("generarNotificacion");
					log.info("Metodo="+jpdMethod);
					log.info("url="+url);
				}
				
				SOAPMessage responseWebServ = con.call(message, url);
				W83bClsTrazas.trazaError(null, " @@@@@@  6 generarNotificacion",null  );
				result = W83bWebServiceCall.getResultado(responseWebServ);
				W83bClsTrazas.trazaError(null, " @@@@@@  24 result: " +result,null);
			
			}
			
			if (log.isLoggable(Level.INFO)){
				log.info("sessionToken="+sessionToken);
				log.info("tareaNotificar="+tareaNotificar);
				//log.info("resultado sin decodificar generar notificacion-->" + result);
			}
		
			return result;				

			
		} catch (IOException ioe) {
			return "";
		} catch (Exception ex) {
			return "";
		}

	}
	public static String publicarNotificacion(String sessionToken, String sUnsignedNotification,String bytesFirma) {
		String result = "";

		try {
			W83bClsTrazas.trazaError(null, "===> 1 en publicarNotificacion",null);
	           Date fecha=new Date();
	            String sfecha=W83bDateUtils.dateTimeToString(fecha);
	           
	    		BufferedWriter out = new BufferedWriter(new FileWriter(W83bProperties.getProperty("w83b", "file.out")+"publicarNotificacion.txt",true));
	            out.write(sfecha+"\r\n\r\n"+"sessionToken=>"+sessionToken+"\r\n\r\n"+"tareaNotificar=>"+sUnsignedNotification+"\r\n\r\n"+"bytesNotification=>"+bytesFirma+"\r\n\r\n");
	         
				out.close();
				
			if(W83bProperties.getProperty("w83b","notificar.crear.ACTIVE").equals("true")){
				String jpdMethod = W83bProperties.getProperty("w83b","notificacion.procedure.publicar");
				
				MessageFactory mfactory = MessageFactory.newInstance();
				
				SOAPMessage message = mfactory.createMessage();
				
				SOAPPart soapPart = message.getSOAPPart();
				
				SOAPEnvelope envelope = soapPart.getEnvelope();

				SOAPBody body = envelope.getBody();
				
				Name name = envelope.createName(jpdMethod, "",
						"http://www.openuri.org/");
				
				
				SOAPBodyElement element = body.addBodyElement(name);
				

				SOAPElement symbol = element.addChildElement(envelope.createName("sSessionToken"));
				
				
				symbol.addTextNode(sessionToken);
				symbol = element.addChildElement(envelope.createName("sUnsignedNotification"));
				
				symbol.addTextNode(sUnsignedNotification);

				
				symbol = element.addChildElement(envelope.createName("bytesNotification"));
				
				symbol.addTextNode(bytesFirma);

			
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				
				SOAPConnection con = factory.createConnection();
				
				String url = W83bProperties.getProperty("w83b",
						"url.ws.crearNotificacion");
				
				

				if (log.isLoggable(Level.INFO)){
					log.info("publicarNotificacion");
					log.info("Metodo="+jpdMethod);
					log.info("url="+url);
				}
				W83bClsTrazas.trazaError(null, "===> 26 ",null);
				if (log.isLoggable(Level.INFO)){
					log.info("***message="+message);
				}
				SOAPMessage responseWebServ = con.call(message, url);
				W83bClsTrazas.trazaError(null, "===> 27 responseWebServ:"+responseWebServ,null);
				result = W83bWebServiceCall.getResultado(responseWebServ);
				W83bClsTrazas.trazaError(null, "===> 28 result:"+result,null);
			}else{

				result = "";


			}
		
			if (log.isLoggable(Level.INFO)){
				log.info("sessionToken="+sessionToken);
				log.info("sUnsignedNotification="+sUnsignedNotification);
				log.info("bytesNotification="+bytesFirma);
				log.info("-->" + result);
			}
		
			if (result.startsWith("Fallo")){
				result="";
			}
		
			
			return result;
			
		} catch (IOException ioe) {
			W83bClsTrazas.trazaError(null, "===> IOException",null);
			result="";
			
		} catch (Exception ex) {
			W83bClsTrazas.trazaError(null, "===> Exception",null);
			result="";
		}

		return result;
	}
	
	public static String comprobarFirma(String sessionToken, String documento, String bytesFirma) {
		String result = "";

		try {
			W83bClsTrazas.trazaError(null, "===> 1 en comprobarfirma",null);

			
			BufferedWriter out = new BufferedWriter(new FileWriter(W83bProperties.getProperty("w83b", "file.out")+"comprobarFirma.txt",true));
    		 out.write("\r\n\r\n"+"sessionToken=>"+sessionToken+"\r\n\r\n"+"documento=>"+documento+"\r\n\r\n"+"bytesFirma"+bytesFirma+"\r\n\r\n");
          out.close();
			
				String jpdMethod = "verifySimplelSignByteArray";
				
				MessageFactory mfactory = MessageFactory.newInstance();
				
				SOAPMessage message = mfactory.createMessage();
				
				SOAPPart soapPart = message.getSOAPPart();
				
				SOAPEnvelope envelope = soapPart.getEnvelope();
				
				SOAPBody body = envelope.getBody();
				
				Name name = envelope.createName(jpdMethod, "",
				"http://www.openuri.org/");
				
			
				SOAPBodyElement element = body.addBodyElement(name);
				

				SOAPElement symbol = element.addChildElement(envelope.createName("sSecurityToken"));
				
				
				symbol.addTextNode(sessionToken);
				symbol = element.addChildElement(envelope.createName("simpleSign"));
				
				symbol.addTextNode(bytesFirma);
				
				
				symbol = element.addChildElement(envelope.createName("documents"));
				
				symbol.addTextNode(documento);
				
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				
				SOAPConnection con = factory.createConnection();
				
				String url = W83bProperties.getProperty("w83b",
				"url.ws.Q99vDigitalSignatureJWS");
				
				
				if (log.isLoggable(Level.INFO)){
					log.info("comprobarFirma");
					log.info("Metodo="+jpdMethod);
					log.info("url="+url);
				}
				W83bClsTrazas.trazaError(null, "===> 26 ",null);
				if (log.isLoggable(Level.INFO)){
					log.info("***message="+message);
				}
				SOAPMessage responseWebServ = con.call(message, url);
				W83bClsTrazas.trazaError(null, "===> 27 responseWebServ:"+responseWebServ,null);
				result = W83bWebServiceCall.getResultado(responseWebServ);
				W83bClsTrazas.trazaError(null, "===> 28 result:"+result,null);
		
			
			if (log.isLoggable(Level.INFO)){
				log.info("sessionToken="+sessionToken);
				//log.info("sUnsignedNotification="+sUnsignedNotification);
				//log.info("bytesNotification="+bytesFirma);
				log.info("-->" + result);
			}
			
			if (result.startsWith("Fallo")){
				result="";
			}
			
			
			return result;
			
		} catch (IOException ioe) {
			W83bClsTrazas.trazaError(null, "===> IOException",null);
			result="";
			
		} catch (Exception ex) {
			W83bClsTrazas.trazaError(null, "===> Exception",null);
			result="";
		}
		
		return result;
	}
	
	private static final Logger log = Logger.getLogger(W83bEjGvDocumento.class.getName());
}
